package cn.jbolt.core.base;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.core.model.base.JBoltModelConfig;
import com.jfinal.core.converter.TypeConverter;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 封装JBolt自己的Model和Bean的Injector
 *
 * @ClassName: JBoltInjector
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2019年11月13日
 */
public class JBoltInjector {

	private static <T> T createInstance(Class<T> objClass) {
		try {
			return objClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> T injectModel(Class<T> modelClass, HttpServletRequest request, boolean skipConvertError) {
		String modelName = modelClass.getSimpleName();
		return (T) injectModel(modelClass, StrKit.firstCharToLowerCase(modelName), request, skipConvertError);
	}

	public static <T> T injectBean(Class<T> beanClass, HttpServletRequest request, boolean skipConvertError) {
		String beanName = beanClass.getSimpleName();
		return (T) injectBean(beanClass, StrKit.firstCharToLowerCase(beanName), request, skipConvertError);
	}

	public static final <T> T injectBean(Class<T> beanClass, String beanName, Map<String, Object> parasMap) {
		return injectBean(beanClass, beanName, parasMap, false);
	}

	@SuppressWarnings("unchecked")
	public static final <T> T injectBean(Class<T> beanClass, String beanName, Map<String, Object> parasMap,
			boolean skipConvertError) {
		Object bean = createInstance(beanClass);
		String modelNameAndDot = StrKit.notBlank(beanName) ? beanName + "." : null;
		TypeConverter converter = TypeConverter.me();
		Method[] methods = beanClass.getMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			if (!methodName.startsWith("set") || methodName.length() <= 3) { // only setter method
				continue;
			}
			Class<?>[] types = method.getParameterTypes();
			if (types.length != 1) { // only one parameter
				continue;
			}

			String attrName = StrKit.firstCharToLowerCase(methodName.substring(3));
			String paraName = modelNameAndDot != null ? modelNameAndDot + attrName : attrName;
			if (parasMap.containsKey(paraName)) {
				try {
					Object paraValue = parasMap.get(paraName);
					Object value = paraValue != null ? converter.convert(types[0], paraValue.toString()) : null;
					method.invoke(bean, value);
				} catch (Exception e) {
					if (skipConvertError == false) {
						throw new RuntimeException(e);
					}
				}
			}
		}

		return (T) bean;
	}

	@SuppressWarnings("unchecked")
	public static <T> T injectBean(Class<T> beanClass, String beanName, HttpServletRequest request,
								   boolean skipConvertError) {
		Object bean = createInstance(beanClass);
		String modelNameAndDot = StrKit.notBlank(beanName) ? beanName + "." : null;
		TypeConverter converter = TypeConverter.me();
		Map<String, String[]> parasMap = request.getParameterMap();
		Method[] methods = beanClass.getMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			if (methodName.startsWith("set") == false || methodName.length() <= 3) { // only setter method
				continue;
			}
			Class<?>[] types = method.getParameterTypes();
			if (types.length != 1) { // only one parameter
				continue;
			}

			String attrName = StrKit.firstCharToLowerCase(methodName.substring(3));
			String paraName = modelNameAndDot != null ? modelNameAndDot + attrName : attrName;
			if (parasMap.containsKey(paraName)) {
				try {
					String paraValue = request.getParameter(paraName);
					Object value = paraValue != null ? converter.convert(types[0], paraValue) : null;
					method.invoke(bean, value);
				} catch (Exception e) {
					if (skipConvertError == false) {
						throw new RuntimeException(e);
					}
				}
			}
		}

		return (T) bean;
	}

	@SuppressWarnings("unchecked")
	public static <T> T injectModel(Class<T> modelClass, String modelName, HttpServletRequest request,
									boolean skipConvertError) {
		Object temp = createInstance(modelClass);
		if (!(temp instanceof Model)) {
			throw new IllegalArgumentException("getModel only support class of Model, using getBean for other class.");
		}

		Model<?> model = (Model<?>) temp;
		Table table = TableMapping.me().getTable(model.getClass());
		if (table == null) {
			throw new ActiveRecordException("The Table mapping of model: " + modelClass.getName()
					+ " not exists or the ActiveRecordPlugin not start.");
		}

		String modelNameAndDot = StrKit.notBlank(modelName) ? modelName + "." : null;
		Map<String, String[]> parasMap = request.getParameterMap();
		TypeConverter converter = TypeConverter.me();
		// 对 paraMap进行遍历而不是对table.getColumnTypeMapEntrySet()进行遍历，以便支持
		// CaseInsensitiveContainerFactory
		// 以及支持界面的 attrName有误时可以感知并抛出异常避免出错
		for (Entry<String, String[]> entry : parasMap.entrySet()) {
			String paraName = entry.getKey();
			String attrName;
			if (modelNameAndDot != null) {
				if (paraName.startsWith(modelNameAndDot)) {
					attrName = paraName.substring(modelNameAndDot.length());
				} else {
					continue;
				}
			} else {
				attrName = paraName;
			}
			Class<?> colType = null;
			//直接去数据库字段里找有没有 如果有 就直接用 比如enable id之类的字段
			if (table.hasColumnLabel(attrName)) {
				colType = table.getColumnType(attrName);
			} else {
				//如果没有 说明传的可能是数据库字段转为java属性后不相同导致的 比如 user_id 转为 userId 传的是userId
				if (!attrName.contains("_")) {
					//只能是没有带下划线的过来 带了下划线的不行 因为他是通过java属性传递的时候 就不能有下划线了 直接从配置表里找到数据库的字段名使用
//					attrName = StrUtil.toUnderlineCase(attrName);
					String columnName = JBoltModelConfig.me.modelAttrToColumn((Class<? extends Model>) modelClass,attrName);
					if(columnName == null){
						if (skipConvertError) {
							continue;
						} else {
							throw new ActiveRecordException("The model attribute " + attrName + " is not exists.");
						}
					}
					if (table.hasColumnLabel(columnName)) {
						colType = table.getColumnType(columnName);
					}
					attrName = columnName;
				}
			}
			if (colType == null) {
				if (skipConvertError) {
					continue;
				} else {
					throw new ActiveRecordException("The model attribute " + attrName + " is not exists.");
				}
			}

			try {
				String[] paraValueArray = entry.getValue();
				String paraValue = (paraValueArray != null && paraValueArray.length > 0) ? paraValueArray[0] : null;

				Object value = paraValue != null ? converter.convert(colType, paraValue) : null;
				model.set(attrName, value);
			} catch (Exception e) {
				if (!skipConvertError) {
					throw new RuntimeException("Can not convert parameter: " + paraName, e);
				}
			}
		}

		return (T) model;
	}

	public static final <T> T injectModel(Class<T> modelClass, String modelName, Map<String, Object> parasMap) {
		return injectModel(modelClass, modelName, parasMap, false);
	}

	@SuppressWarnings("unchecked")
	public static final <T> T injectModel(Class<T> modelClass, String modelName, Map<String, Object> parasMap,
			boolean skipConvertError) {
		Object temp = createInstance(modelClass);
		if (!(temp instanceof Model)) {
			throw new IllegalArgumentException("getModel only support class of Model, using getBean for other class.");
		}

		Model<?> model = (Model<?>) temp;
		Table table = TableMapping.me().getTable(model.getClass());
		if (table == null) {
			throw new ActiveRecordException("The Table mapping of model: " + modelClass.getName()
					+ " not exists or the ActiveRecordPlugin not start.");
		}

		String modelNameAndDot = StrKit.notBlank(modelName) ? modelName + "." : null;
		TypeConverter converter = TypeConverter.me();
		// 对 paraMap进行遍历而不是对table.getColumnTypeMapEntrySet()进行遍历，以便支持
		// CaseInsensitiveContainerFactory
		// 以及支持界面的 attrName有误时可以感知并抛出异常避免出错
		for (Entry<String, Object> entry : parasMap.entrySet()) {
			String paraName = entry.getKey();
			String attrName;
			if (modelNameAndDot != null) {
				if (paraName.startsWith(modelNameAndDot)) {
					attrName = paraName.substring(modelNameAndDot.length());
				} else {
					continue;
				}
			} else {
				attrName = paraName;
			}
			Class<?> colType = null;
			if (table.hasColumnLabel(attrName)) {
				colType = table.getColumnType(attrName);
			} else {
				if (!attrName.contains("_")) {
					attrName = StrUtil.toUnderlineCase(attrName);
					if (table.hasColumnLabel(attrName)) {
						colType = table.getColumnType(attrName);
					}
				}
			}
			if (colType == null) {
				if (skipConvertError) {
					continue;
				} else {
					throw new ActiveRecordException("The model attribute " + attrName + " is not exists.");
				}
			}

			try {
				Object paraValue = entry.getValue();
				Object value = paraValue != null ? converter.convert(colType, paraValue.toString()) : null;
				model.set(attrName, value);
			} catch (Exception e) {
				if (!skipConvertError) {
					throw new RuntimeException("Can not convert parameter: " + paraName, e);
				}
			}
		}

		return (T) model;
	}

}
